import globalData from './config'
import Axios from 'axios'
import Vue from 'vue';
import { Toast } from 'vant';
Vue.use(Toast);

/**
 * 请求前的操作
 * @type {string}
 */
function beforeRequest(config) {
    config.headers['x-apiKey'] = globalData.apiKey
    
    Toast.loading({
        message: '加载中...',
        forbidClick: true,
      });

}

/**
 * 请求后处理
 * @type {string}
 */
function afterRequest(response){
    if(response){
        Toast.clear()
    }
}

/**
 * 得到相应的数据
 */
function getResponseData(response){
    if(response.data){
        return response.data
    }
    return response
}

/**
 * 错误处理
 * @type {string}
 */
function afterError(response){
    if(response.msg){
      Toast(response.msg)
    }
    
}
/**
 * post请求成功后错误处理
 * @type {string}
 */
function successMsg(data,showError){
    let code=data.code
    if(code==200){
        if(showError){
            Toast(data.msg)
        }
    }

}







Axios.defaults.baseURL=globalData.baseUrl
Axios.interceptors.request.use(config=>{
    beforeRequest(config)
    return config
})
Axios.interceptors.response.use(response=>{
    afterRequest(response)
    return response
},error=>{
    afterRequest(error)
    if(error.msg){
        afterError(error)
    }
    return Promise.reject(error)
})

function get(url,params,showError){
    return new Promise((resolve,reject)=>{
        Axios.get(url,{
            params:params
        }).then(res=>{
            let data=getResponseData(res)
            resolve(data)
            successMsg(res.data,showError)
        },err=>{
            reject(err)
        })
    })
}
function post(url,params,showError){
    return new Promise((resolve,reject)=>{
        Axios.post(url,params).then(res=>{
            let data=successMsg(res.data,showError)
            resolve(data)
        },err=>{
            reject(err)
        })
    })
}

function upload(url,params,callback1,callback2){
        Axios({
            url:url,
            method:'post',
            data:params,
            onUploadProgress:function(progressEvent){
                if(progressEvent.lengthComputable){
                    callback1(progressEvent)
                }
            }
        }).then(res=>{
            callback2(res)
        },err=>{
            console.log(err)
        })
}


export {get}
export {post}
export {upload}
export default Axios
